package com.tos.second.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tos.second.common.handler.ChatWebSocketHandler;
import com.tos.second.entity.ChatMessage;
import com.tos.second.mapper.ChatMessageMapper;
import com.tos.second.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ChatServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatService {
    
    @Autowired
    private ChatMessageMapper chatMessageMapper;
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    /**
     * 保存消息
     */
    @Override
    public void saveMessage(ChatMessage message) {
        message.setCreateTime(LocalDateTime.now());
        message.setIsRead(0); // 默认未读
        chatMessageMapper.insert(message);
        
        // 缓存到Redis
        String key = "chat:unread:" + message.getReceiverId();
        redisTemplate.opsForList().leftPush(key, JSON.toJSONString(message));
        
        // 尝试实时推送消息
        //this.pushMessageToUser(message);
    }
    
    /**
     * 标记消息为已读
     */
    @Override
    public void markAsRead(Long messageId) {
        chatMessageMapper.updateReadStatus(messageId);
    }
    
    /**
     * 获取用户未读消息
     */
    @Override
    public List<ChatMessage> getUnreadMessages(Long userId) {
        String key = "chat:unread:" + userId;
        List<String> messages = redisTemplate.opsForList().range(key, 0, -1);
        return messages.stream().map(s -> JSON.parseObject(s, ChatMessage.class)).toList();
    }
    
    /**
     * 更新用户在线状态
     */
    @Override
    public void updateUserOnlineStatus(Long userId, boolean online) {
        String key = "user:online:" + userId;
        if (online) {
            redisTemplate.opsForValue().set(key, "1", 30, TimeUnit.MINUTES); // 30分钟过期
        } else {
            redisTemplate.delete(key);
        }
    }
    
    /**
     * 查询用户是否在线
     */
    @Override
    public boolean isUserOnline(Long userId) {
        String key = "user:online:" + userId;
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }
    
    /**
     * 获取历史消息
     */
    @Override
    public List<ChatMessage> getHistoryMessages(Long senderId, Long receiverId, int page, int size) {
        LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq(ChatMessage::getSenderId, senderId).eq(ChatMessage::getReceiverId, receiverId)
                        .or()
                        .eq(ChatMessage::getSenderId, receiverId).eq(ChatMessage::getReceiverId, senderId))
                .orderByDesc(ChatMessage::getCreateTime)
                .last("LIMIT " + (page * size) + "," + size);
        
        return chatMessageMapper.selectList(queryWrapper);
    }
    
    /**
     * 推送消息给用户
     */
//    private void pushMessageToUser(ChatMessage message) {
//        try {
//            // 直接通过WebSocket发送消息给接收者
//            boolean sent = ChatWebSocketHandler.sendMessageToUser(message.getReceiverId(), message);
//            if (sent) {
//                log.info("消息已成功推送至用户: {}", message.getReceiverId());
//            } else {
//                log.info("用户 {} 不在线，消息将保留在未读列表中", message.getReceiverId());
//            }
//        } catch (Exception e) {
//            log.error("推送消息失败: {}", e.getMessage());
//        }
//    }
}